package com.podmanager.UI;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import com.podmanager.audio.MusicService;
import com.podmanager.data.DBContentProvider;
import com.podmanager.data.PMDatabase;
import com.podmanager.data.Playlist;

import android.app.AlertDialog;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.FilterQueryProvider;


public class PlaylistFragment extends ListFragment  
						implements LoaderManager.LoaderCallbacks<Cursor> {
	
	static final String OLD_TO_NEW = "Oldest to Newest";
	static final String PODCAST_THEN_OLD_TO_NEW = "Podcast then oldest to newest";
	static final String NEW_TO_OLD = "Newest to oldest";
	static final String PODCAST_THEN_NEW_TO_OLD = "Podcast then newest to oldest";
	static final String EPISODE_TITLE = "Episode Title";
	static final private int PLAYLIST_LOADER_ID=300;

	private Spinner playlist_sort_dropdown;
	public static final String ARG_SECTION_NUMBER = "section_number";
	private SimpleCursorAdapter mListAdapter;
	private static String SORT;

	private int prev_dropdown_position = -1;
	
	private String[] columns = { 
			PMDatabase.EPISODES.TABLE_NAME + "." + PMDatabase.EPISODES.EPI_TITLE, 
			PMDatabase.EPISODES.TABLE_NAME + "." + PMDatabase.EPISODES.EPI_DATE, 
			PMDatabase.SUBSCRIPTIONS.TABLE_NAME + "." + PMDatabase.SUBSCRIPTIONS.SUB_TITLE,
			PMDatabase.EPISODES.TABLE_NAME + "." +PMDatabase.EPISODES.EPI_DESCRIPTION,
			PMDatabase.EPISODES.TABLE_NAME + "." + PMDatabase.EPISODES.KEY_ROW_ID};
			//PMDatabase.EPISODES.SUB_ROW_ID,
			//PMDatabase.EPISODES.TABLE_NAME + "." +PMDatabase.EPISODES.EPI_DESCRIPTION};
	private int[] to = { R.id.playlist_item_episode_title, 
			R.id.playlist_item_date,
			R.id.playlist_item_subscription_title,
			R.id.playlist_item_duration
		};

	private static String SELECTION	=PMDatabase.EPISODES.IS_IN_PLAYLIST +"=1";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
 
 //       Bundle args = getArguments();
 
        View rootView = inflater.inflate(R.layout.playlist_layout, container, false);
        
        playlist_sort_dropdown = (Spinner) rootView.findViewById(R.id.playlist_sort_dropdown);
    	this.playlist_sort_dropdown.setOnItemSelectedListener(new OnItemSelectedListener(){
			@Override
			public void onItemSelected(AdapterView<?> spinner, View view,
					int position, long id) {
				
				if(position == prev_dropdown_position)
					return;
				prev_dropdown_position = position;
				String subscription_title = spinner.getItemAtPosition(position).toString();

        		//TODO update adapter for listview to use a query that is sorted as selected
				//will probably require a switch or if/else in order to apply required query
				Toast.makeText(spinner.getContext(),subscription_title, Toast.LENGTH_SHORT).show(); 
				
				selectSortOption(subscription_title);	
			}
			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
			}
    	});
		mListAdapter = new SimpleCursorAdapter(getActivity(), 
				R.layout.playlist_item_layout, null, 
				columns, to, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
		setListAdapter(mListAdapter);
		LoaderManager loaderManager = this.getLoaderManager();
		loaderManager.initLoader(PLAYLIST_LOADER_ID, null, this);
		mListAdapter.setFilterQueryProvider(new FilterQueryProvider(){
			@Override
			public Cursor runQuery(CharSequence constraint) {
				return getActivity().getContentResolver().query(
						DBContentProvider.PLAYLIST_URI,
						columns, SELECTION,	null,	SORT);
			} 
		});
		setListAdapter(mListAdapter);

        return rootView;
    }
    
	private void selectSortOption(String subscription_title) {
		SORT = null; 
		
		if (subscription_title.compareTo(OLD_TO_NEW) == 0) {
			SORT = PMDatabase.EPISODES.TABLE_NAME + "." + PMDatabase.EPISODES.EPI_DATE + " ASC";
		}
		else if (subscription_title.compareTo(PODCAST_THEN_OLD_TO_NEW) == 0) {
			SORT = PMDatabase.EPISODES.TABLE_NAME + "." + PMDatabase.EPISODES.EPI_TITLE + " ASC" + ", " + PMDatabase.EPISODES.EPI_DATE + " ASC";
		}
		else if (subscription_title.compareTo(NEW_TO_OLD) == 0) {
			SORT = PMDatabase.EPISODES.TABLE_NAME + "." + PMDatabase.EPISODES.EPI_DATE + " DESC";
		}
		else if (subscription_title.compareTo(PODCAST_THEN_NEW_TO_OLD) == 0) {
			SORT = PMDatabase.EPISODES.TABLE_NAME + "." +PMDatabase.EPISODES.EPI_TITLE + " ASC" + ", " + PMDatabase.EPISODES.EPI_DATE + " DESC";
		}
		else if (subscription_title.compareTo(EPISODE_TITLE) == 0) {
			SORT = PMDatabase.EPISODES.TABLE_NAME + "." +PMDatabase.EPISODES.EPI_TITLE;
		}
		
		if (SORT != null) 
			updateSettings(mListAdapter);
		
	}
	
	private void updateSettings(SimpleCursorAdapter mListAdapter) {
		try {				
			mListAdapter.getFilter().filter("");
			setListAdapter(mListAdapter);
			Playlist playlist = Playlist.getPlaylist();
			playlist.updatePlaylist(getActivity().getContentResolver(), SORT);
			
			Map<String, String> settings = new HashMap<String, String>();
			settings.put("SORT", SORT);
			settings.put("FILE", playlist.getFirstItem());
			
			playlist.insertSettings(settings, getActivity().getContentResolver());
		} catch (Exception e) {
			e.printStackTrace();
			Log.e("ContentProvider", e.getLocalizedMessage());
		}
	}

	@Override
	public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
		return new CursorLoader(this.getActivity(), DBContentProvider.PLAYLIST_URI,
				columns, SELECTION, null, SORT);
	}
	
    @Override
    public void onListItemClick(ListView l, View v, int position, long list_RowID) {
		new AsyncTask<String, Void, String>(){
			@Override
			protected String doInBackground(String... params) { 
				String [] columns = new String[]{PMDatabase.EPISODES.FILE_PATH};
				String selection= PMDatabase.EPISODES.KEY_ROW_ID+"="+params[0];
				Cursor c =getActivity().getContentResolver().query(DBContentProvider.EPISODES_URI,//URI/table 
						columns, selection, null, null);//columns, selection, arguments, sort
				if(c==null)return null;
				if(c.getCount()<1)return null;
				
				c.moveToFirst();
				String file=c.getString(c.getColumnIndex(columns[0]));
				c.close();
				if(!new File(file).exists())
					file=null;//if the file doesn't exist, pass null so next onPost doesn't try to play it.
				// get the next file (i'm guessing this is the place to do it)
				Playlist playlist = Playlist.getPlaylist();
				if (!playlist.isPlaylistEmpty())
					playlist.updateCurrentItem(getActivity().getContentResolver(), file);
				
				return file;
			}
			@Override
			protected void onPostExecute(String result) {
				super.onPostExecute(result);
				if(result==null || result.equals(""))
				{
					AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

					// 2. Chain together various setter methods to set the dialog characteristics
					builder.setMessage("Perhaps try downloading the file first")
					       .setTitle("File Not Available")
					       .setPositiveButton("OK", null)
					       .show();
					return;
				}
				Bundle b=new Bundle();
				b.putString(MusicService.FILE_TO_PLAY, result);
				MusicService.doStartMusicService(getActivity(), MusicService.ACTION_PLAY_THIS, b);
			}}
		.execute(""+list_RowID);
    }
    
	@Override
	public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {
		try {
			mListAdapter.swapCursor(arg1);
		} catch (Exception e) 
			{ Log.e("playlist", e.getMessage()); }
	}

	@Override
	public void onLoaderReset(Loader<Cursor> arg0) {
		mListAdapter.swapCursor(null);
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		
		//kept getting weird "attempt to re-open an already-closed object: android.database.sqlite.SQLiteQuery" error
		//it was occuring whenever Fragment was re-created, so I'm destroying the loader
		this.getLoaderManager().destroyLoader(PlaylistFragment.PLAYLIST_LOADER_ID);
	}

}
